package itbour.onetouchshow.activity.challengezone.video;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.IOException;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.adapter.MusicListAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseActivity;
import itbour.onetouchshow.bean.BasePageData;
import itbour.onetouchshow.bean.MusicInfoBean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.T_;

/**
 * Created by guoh on 2018/7/6.
 * 功能描述：背景音乐列表
 * 需要的参数：
 */
public class MusicListActivity extends MVPBaseActivity<MusicListView, MusicListPresenter> implements MusicListView {

    private static final int FAST_CLICK_DELAY_TIME = 1000;
    @BindView(R.id.ls_music_list)
    ListView lsMusicList;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private long lastClickTime = 0L;
    //音乐播放器
    private MediaPlayer mediaPlayer;
    //列表适配器
    private MusicListAdapter adapter;
    //当前点击的position
    private int clickPosition;
    //当前播放时间
    private float currentPlayTime = 0;
    //定时器
    private Handler timeHandler;
    private Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            currentPlayTime += 1;
            adapter.getItem(clickPosition).setProgress((int) (currentPlayTime / adapter.getItem(clickPosition).getBgmDuration() * 100));
            adapter.notifyDataSetChanged();
            timeHandler.postDelayed(this, 1000);
        }
    };
    private BroadcastReceiver headsetPlugReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(action)) {
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    onMusicItemClick(clickPosition);
                }
            }
        }

    };

    public static Intent getLaunchIntent(Context context) {
        Intent intent = new Intent(context, MusicListActivity.class);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.ac_music_list;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        timeHandler = new Handler();
        adapter = new MusicListAdapter(getViewContext());
        lsMusicList.setAdapter(adapter);
        lsMusicList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onMusicItemClick(position);
            }
        });
        adapter.setItemClickListener(new MusicListAdapter.onItemClickListener() {
            @Override
            public void onMusicPlayClick(int position) {
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                onMusicItemClick(position);
            }

            @Override
            public void onUseNowClick(int position) {
                if (adapter.getItem(clickPosition).isPlay()) {
                    pausePlayBgm();
                }
                releaseMediaPlayer();
                Intent intent = new Intent();
                intent.putExtra(AppConst.KEY_BGM_BEAN, adapter.getItem(position));
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        mPresenter.getMusicList(false);
        initRefreshLayout();
        initMediaPlayer();
        registerHeadsetPlugReceiver();
    }

    private void onMusicItemClick(int position) {
        clickPosition = position;
        //已经显示完全的 只改变播放图标
        if (adapter.getItem(position).isFullShow()) {
            //全部显示
            boolean isPlay = adapter.getItem(position).isPlay();
            if (isPlay) {
                //正在播放 则暂停
                pausePlayBgm();
            } else {
                //暂停 则继续播放
                reStartPlayBgm();
            }
            adapter.getItem(position).setPlay(!isPlay);
            adapter.notifyDataSetChanged();
        } else {
            // 设置所有的先恢复原来样式
            for (MusicInfoBean bean : adapter.getData()) {
                bean.setFullShow(false);
                bean.setPlay(false);
                bean.setProgress(0);
            }

            //设置当前点击项展开样式
            adapter.getItem(position).setPlay(true);
            adapter.getItem(position).setFullShow(true);
            adapter.getItem(position).setProgress(0);
            adapter.notifyDataSetChanged();
            releaseMediaPlayer();
            initMediaPlayer();
            startPlayBgm(adapter.getItem(position).getUrl(), position);
        }
    }

    //初始化播放器
    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
    }

    //释放音乐播放器
    private void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
            timeHandler.removeCallbacks(timeRunnable);
            currentPlayTime = 0;
        }
    }

    //暂停播放音乐
    private void pausePlayBgm() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            timeHandler.removeCallbacks(timeRunnable);
        }
    }

    //重新开始播放音乐
    private void reStartPlayBgm() {
        if (mediaPlayer != null) {
            mediaPlayer.start();
            timeHandler.post(timeRunnable);
        }
    }

    //根据地址开始播放音乐
    private void startPlayBgm(String url, int position) {
        try {
            mediaPlayer.setDataSource(this, Uri.parse(url));
        } catch (IOException e) {
            e.printStackTrace();
            T_.showCustomToast("播放出错,找不到该音频");
        }
        mediaPlayer.prepareAsync();
        mediaPlayer.seekTo(0);
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                adapter.getItem(position).setBgmDuration(mp.getDuration() / 1000);
                timeHandler.post(timeRunnable);
                adapter.notifyDataSetChanged();
                mp.start();
            }
        });
    }

    //初始化刷新
    private void initRefreshLayout() {
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setEnableLoadMoreWhenContentNotFull(true);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {

            }

        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getMusicList(true);
            }
        });
    }

    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {

    }

    @OnClick(R.id.ll_close)
    public void onViewClicked() {
        if (adapter.getItem(clickPosition).isPlay()) {
            pausePlayBgm();
        }
        releaseMediaPlayer();
        finish();
    }

    @Override
    public void loadMusicListSuccess(BasePageData pageData, boolean loadMore) {
        if (pageData.list != null && pageData.list.size() != 0 && !loadMore) {
            adapter.replaceAll(pageData.list);
        } else {
            adapter.addAll(pageData.list);
        }
        if (loadMore) {
            if (pageData.list == null || pageData.list.size() == 0) {
                finishLoadMoreAndToast();
            } else {
                refreshLayout.finishLoadMore(true);
            }
        }
    }

    @Override
    public void loadMusicListFail(String info) {

    }

    @Override
    public void noMoreData() {
        finishLoadMoreAndToast();
    }

    private void finishLoadMoreAndToast() {
        refreshLayout.finishLoadMoreWithNoMoreData();
        T_.showCustomToast("没有更多数据");
    }

    //到后台界面暂停播放音乐
    @Override
    protected void onPause() {
        super.onPause();
        pausePlayBgm();
        if (adapter.getItem(clickPosition) != null && adapter.getItem(clickPosition).isPlay()) {
            adapter.getItem(clickPosition).setPlay(false);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onBackPressed() {
        if (adapter.getItem(clickPosition) != null && adapter.getItem(clickPosition).isPlay()) {
            pausePlayBgm();
        }
        releaseMediaPlayer();
        super.onBackPressed();
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(headsetPlugReceiver);
        super.onDestroy();
    }

    private void registerHeadsetPlugReceiver() {
        IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
        registerReceiver(headsetPlugReceiver, intentFilter);
    }
}
